package cn.elead.chaos.shiro.configuration;

import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import cn.elead.chaos.shiro.exception.ShiroExceptionResolverService;
import cn.elead.chaos.shiro.rest.AuthEndpoint;
import cn.elead.chaos.shiro.service.IShiroRealmService;
import cn.elead.chaos.shiro.service.impl.ShiroRealmService;

/**
 * 权限配置加载
 * <p>
 * https://www.jianshu.com/p/0b1131be7ace<br>
 * https://github.com/chilexun/springboot-demo
 * 
 * @author luopeng
 */
@Configuration
public class ShiroBeanConfiguration {

	/**
	 * 模拟用户权限
	 * 
	 * @return
	 */
	@Bean
	@ConditionalOnMissingBean(IShiroRealmService.class)
	public IShiroRealmService shiroRealmService() {
		return new ShiroRealmService();
	}

	/**
	 * 权限信息端点
	 * 
	 * @return
	 */
	@Bean
	@ConditionalOnMissingBean(AuthEndpoint.class)
	public AuthEndpoint authEndpoint(Environment environment) {
		return new AuthEndpoint(environment);
	}

	/**
	 * 异常处理
	 * 
	 * @return
	 */
	@Bean
	public ShiroExceptionResolverService shiroExceptionResolverService() {
		return new ShiroExceptionResolverService();
	}

	/**
	 * 解决spring aop和注解配置一起使用的bug。如果您在使用shiro注解配置的同时，<br>
	 * 引入了spring aop的starter，会有一个奇怪的问题，导致shiro注解的请求，不能被映射<br>
	 * 用于解决一个奇怪的bug。在引入spring aop的情况下。 <br>
	 * 在@Controller注解的类的方法中加入@RequiresRole等shiro注解，会导致该方法无法映射请求，导致返回404。 加入这项配置能解决这个bug
	 * 
	 * @return
	 */
	@Bean
	public static DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
		DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
		defaultAdvisorAutoProxyCreator.setUsePrefix(true);
		return defaultAdvisorAutoProxyCreator;
	}

}
